import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:gameplay_flutter/lib_basemodel/home/room_list_model.dart';
import 'package:gameplay_flutter/lib_basemodel/home_popular_top/popular_top_model.dart';
import 'package:gameplay_flutter/lib_basemodel/room_category/RoomCategory.dart';
import 'package:gameplay_flutter/lib_basemodel/room_types/room_types_model.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_network/http_api.dart';
import 'package:gameplay_flutter/m_room/room_manager.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../lib_basemodel/chat_room/kh_chat_room_enter_model.dart';
import '../../lib_basemodel/chat_room/kh_chat_room_info_model.dart';
import '../../lib_basemodel/home_popular/home_popular_model.dart';
import '../../lib_network/http_helper.dart';
import '../../m_chatroom/src/interface/room_page.dart';
import '../../resource/language/generated/l10n.dart';

class HomeDataType {
  static const room = 1;
  static const user = 2;
}

class HomeController extends GetxController with GetTickerProviderStateMixin {
  var mainData;
  final recommend = <Recommend>[].obs;
  final topBanners = <TopBanners>[].obs;
  final listBanners = <dynamic>[].obs;
  final popularTopList = <PopularTopList>[].obs;
  final popularList = <Popular>[].obs;
  final roomTagsList = <RoomCategory>[].obs;
  final roomTypesList = <RoomTypesModel>[].obs;
  final recentlyRoomList = <Recommend>[].obs;
  final followingRoomList = <Recommend>[].obs;
  final myRoomList = <Recommend>[].obs;

  late Background? background;
  String? errorMsg;
  late String ids;
  final createState = false.obs;
  final isShowBottom = true.obs;
  final isNew = true.obs;
  final GetStorage  box = GetStorage();


  // late List<GlobalKey<HomeSubPageState>> subPageKeys;

  @override
  void onInit() {
    print('开始执行');
    super.onInit();
    loadRoomTags();
    loadMineTypes();
    loadData('Oman','refresh',1);
  }

  @override
  void onReady() {
    super.onReady();
  }

  joinRoomPage(BuildContext context, model) {
    ///进入房间
    // joinRoomPage
    /// 进入房间要用的模型
    KHChatRoomEnterModel enterModel = KHChatRoomEnterModel();
    enterModel.enterRoomNo = model.roomNo;
    if (model.rangeTypeStr != null) {
      enterModel.rangeType = int.parse(model.rangeTypeStr!);
    }
    enterModel.template = model.roomTemplateId;

    /// 基础数据
    KHChatRoomInfoModel roomInfoModel = KHChatRoomInfoModel();

    roomInfoModel.roomCategoryId = model.roomCategoryId;
    roomInfoModel.icon = model.roomIcon;
    roomInfoModel.roomNo = model.roomNo;
    roomInfoModel.name = model.roomName;
    roomInfoModel.name = model.roomName;
    roomInfoModel.roomTemplateId = model.roomTemplateId;
    roomInfoModel.roomCode = model.roomCode;

    enterModel.roomBaseInfoModel = roomInfoModel;
    if (model.roomNo != null) {
      RoomPage.show(context, model.roomNo!);
    }
  }

  Future loadPopularTop(String? type) async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetPopularTop,
        showLoading: true,
        showToast: true,
        body: {'topType': type, 'period': 1, 'limitStart': 0,'limitEnd':3});
    if (resp.isSuccess && resp.result != null && resp.result['data'] != null){
      var data = PopularTopModel.fromJson(resp.result['data']);
      if(type == '5'){
          popularTopList.add(data.topRoomList as PopularTopList);
      } else {
          popularTopList.add(data.topList as PopularTopList);
      }
      update();
    } else {
      errorMsg = resp.result?['msg'] ?? T.current!.service_error_retry_0;
    }
  }


  //获取popular列表及top数据
  Future loadPopularData(String? type,refresh,pageNum) async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetPopular,
        showLoading: true,
        showToast: true,
        body: {'pageNum': pageNum, 'pageSize': 20, 'roomCategoryIds': type});
    if (resp.isSuccess && resp.result != null) {
      var data = HomePopularModel.fromJson(resp.result);
      if(data.popular!.isNotEmpty){
        if(refresh == 'more'){
          List<Popular> list = popularList.value;
          for(var item in data.popular!){
            list.add(item);
          }
          popularList.value = list;
        } else {
          popularList.value = data.popular!;
        }
        update();
        return true;
      } else {
        if(refresh != 'more'){
          popularList.value = [];
        }
        update();
        return false;
      }
    } else {
      errorMsg = resp.result?['msg'] ?? T.current!.service_error_retry_0;
      return false;
    }
  }

  //获取mini tabs选项卡数据
  Future loadMineTypes() async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetRoomTypes,
        showLoading: true, showToast: true, body: {});
    if (resp.isSuccess && resp.result != null) {
      List<RoomTypesModel> _roomTypeList = [];
      for (var item in resp.result['roomMineTypeList']) {
        var data = RoomTypesModel.fromJson(item);
        _roomTypeList.add(data);
      }
      roomTypesList.value = _roomTypeList;
      update();
    } else {
      errorMsg = resp.result?['msg'] ?? T.current!.service_error_retry_0;
    }
  }

  //根据tabs选项卡获取mine列表数据
  Future loadMineData(int fetchType, int roomType,refresh,pageNum) async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetMineList,
        showLoading: true,
        showToast: true,
        body: {'type': roomType, 'roomCategoryIds': ''});
    if (resp.isSuccess && resp.result != null) {
      List<Recommend> _roomList = [];
      for (var item in resp.result) {
        var data = Recommend.fromJson(item);
        _roomList.add(data);
      }
      if (fetchType == 0) {
        recentlyRoomList.value = _roomList;
      }
      if (fetchType == 1) {
        myRoomList.value = _roomList;
        if(box.read('new_room')!= null){
          for(var item in _roomList){
            if(item.roomNo == box.read('new_room')['roomNo']){
              int timerString = DateTime.now().millisecondsSinceEpoch;
              if(timerString - box.read('new_room')['time'] < 86400000){
                isNew.value = true;
              } else {
                isNew.value = false;
              }
            }
          }
        }
      }
      if (fetchType == 2) {
        followingRoomList.value = _roomList;
      }
      update();
      return false;
    } else {
      errorMsg = resp.result?['msg'] ?? T.current!.service_error_retry_0;
      return false;
    }
  }

  //查询首页recommend数据
  Future loadData(String countries,String type,pageNum) async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetCommend,
        showLoading: true,
        showToast: true,
        body: {'pageNum': pageNum, 'pageSize': 20, 'country': countries});
    if (resp.isSuccess && resp.result != null) {
      var data = RoomListModel.fromJson(resp.result);
      if(data.recommend!.isNotEmpty){
        if(type == 'more'){
          List<Recommend> list = recommend.value;
          for(var item in data.recommend!){
            list.add(item);
          }
          recommend.value = list;
        } else {
          recommend.value = data.recommend!;
        }
        update();
        return true;
      } else {
        if(type != 'more'){
          recommend.value = [];
        }
        update();
        return false;
      }

    } else {
      errorMsg = resp.result?['msg'];
      showToast(errorMsg ?? T.current.service_error_retry_0);
      return false;
    }
  }

  //查询房间类型
  Future loadRoomTags() async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetRoomTages,
        showLoading: true, showToast: true, body: {'scene': '3'});
    if (resp.isSuccess && resp.result != null) {
      late List<RoomCategory> _list = [];
      for (var item in resp.result['items']) {
        _list.add(RoomCategory.fromJson(item));
      }
      roomTagsList.value = _list;
    } else {
      errorMsg = resp.result?['msg'];

      showToast(errorMsg ?? T.current.service_error_retry_0);
    }
  }

  //查询是否可以建房？
  Future CheckRoomState() async {
    var resp = await HttpHelper.instance().post(HttpApi.appGetMineRoomState,
        showLoading: true, showToast: true, body: {'scene': '1'});
    if (resp.isSuccess) {
      return true;
    } else {
      errorMsg = resp.result?['msg'];
      showToast(errorMsg ?? T.current.service_error_retry_0);
      return false;
    }
  }

  //文件转AssetEntity实体
  Future<AssetEntity?> fileToAssetEntity(File file) async {
    DateTime now = DateTime.now();
    int timestampInMilliseconds = now.millisecondsSinceEpoch;
    return await PhotoManager.editor.saveImage(
      await file.readAsBytes(),
      title: file.path.split('/').last,
      filename: '${timestampInMilliseconds}.jpg',
    );
  }

  //上传room图片
  Future uploadImage(image) async {
    DateTime now = DateTime.now();
    int timestampInMilliseconds = now.millisecondsSinceEpoch;
    Map<String, dynamic>? body = {
      'file': 1,
      'name': '${timestampInMilliseconds}.jpg',
    };
    List<AssetEntity> list = [];
    AssetEntity? entity = await fileToAssetEntity(File(image.path));
    list.add(entity!);
    var resp = await HttpHelper.instance()
        .multiUpload(HttpApi.discoverUpload, body, list);
    if (resp != null) {
      return resp.result;
      // update();
    } else {
      errorMsg = resp?.result?.msg ?? T.current!.service_error_retry_0;
      return false;
    }
  }

  //创建房间
  Future createRoom(icon,name,roomCategoryId,slogan,context) async {
    var resp = await HttpHelper.instance().post(HttpApi.appCreateMineRoom,
        showLoading: true,
        showToast: true,
        body: {
          'icon': icon,
          'name': name,
          'roomCategoryId': roomCategoryId,
          'slogan': slogan
        });
    if (resp.isSuccess) {
      showToast('Create room success');
      try{
        final String roomNo =  resp.result['roomNo'];
        int currentTimeMillis = DateTime.now().millisecondsSinceEpoch;
        final  newRoom = {
          "roomNo":roomNo,
          "time":currentTimeMillis
        };
        box.write('new_room', newRoom);
        var roomInfo = Recommend.fromJson(resp.result['data']);
        // joinRoomPage(context,roomInfo);
        RoomManager.instance.joinRoom(roomNo);
      } catch(e){
      }
      return true;
    } else {
      errorMsg = resp.result?['msg'] ?? T.current!.service_error_retry_0;
      showToast(errorMsg ?? T.current.service_error_retry_0);
      return false;
    }
  }

  @override
  void onClose() {
    super.onClose();
  }

  /// 请求房间数据
  void loadRoomData(
    String roomNo, {
    String? pushOrderMsgId,
    String? password,
  }) async {
    // 获取当前时间
    DateTime now = DateTime.now();

    // 获取当前时间的时间戳（毫秒）
    int timestampInMilliseconds = now.millisecondsSinceEpoch;

    var resp = await HttpHelper.instance().post(
      HttpApi.voiceRoomEnterExt,
      showLoading: true,
      showToast: true,
      body: {
        'roomNo': roomNo,
        'timestamp': timestampInMilliseconds,
      },
    );
    if (resp.isSuccess && resp.result != null) {
      // var data = RoomListModel.fromJson(resp.result);
      // recommend.value = data.recommend!;
      // // topBanners = mainData?.data?.banner?.topBanners;
      // // listBanners = mainData?.data?.banner?.listBanners;
      // // background = mainData?.data?.banner?.background;
      // update();
      createState.value = true;
    } else {
      // errorMsg = resp.result?.msg ?? T.current!.service_error_retry_0;
    }
  }
}
